package com.giantlizard.cloud.aop.aspect;

import com.giantlizard.cloud.aop.annotation.DictValue;
import com.giantlizard.cloud.aop.entity.SysDict;
import com.giantlizard.cloud.redis.utils.RedisOperator;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.util.List;

/**
 * 处理 @DictValue 注解的切面
 */
@Aspect
@Component
public class DictValueAspect {

    private final RedisOperator redisOperator;

    public DictValueAspect(@Lazy RedisOperator redisOperator) {
        this.redisOperator = redisOperator;
    }

    @AfterReturning(pointcut = "execution(* com.giantlizard.cloud..*.*(..))", returning = "result")
    public void convertDictValue(JoinPoint joinPoint, Object result) throws IllegalAccessException {
        if (result == null) return;

        Field[] fields = result.getClass().getDeclaredFields();
        for (Field field : fields) {
            if (field.isAnnotationPresent(DictValue.class)) {
                field.setAccessible(true);
                Object code = field.get(result);
                DictValue annotation = field.getAnnotation(DictValue.class);

                if (annotation.enabled() && code != null) {
                    // 从 Redis 中获取字典的所有值
                    List<SysDict> dict = (List<SysDict>) redisOperator.getObject("dict:" + annotation.description());
                    String dictValue = annotation.defaultValue();

                    // 根据属性的值和字典 code 进行比较
                    for (SysDict item : dict) {
                        dictValue = item.getDictCode().equals(code) ? item.getDictValue() : dictValue;
                    }
                    // 找到对应的 name 后缀属性并赋值
                    String nameFieldName = field.getName() + "Name";
                    try {
                        Field nameField = result.getClass().getDeclaredField(nameFieldName);
                        nameField.setAccessible(true);
                        nameField.set(result, dictValue);
                    } catch (NoSuchFieldException e) {
                        // 如果没有对应的 name 后缀属性，忽略
                        System.out.println("没有找到对应的 name 后缀属性：" + nameFieldName);
                    }
                }
            }
        }
    }
} 